package com.orgcent.activities;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.Service;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

/**
 * 访问互联网
 */
public class TestInternetConn extends Activity {

	private static final String TAG = TestInternetConn.class.getSimpleName();
	private TextView result_tv;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.conn_internet);

		result_tv = (TextView) findViewById(R.id.result_tv);
	}

	public void btnOnClick(View view) {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Service.CONNECTIVITY_SERVICE);
		// 是否可以联网
		NetworkInfo ninfo = cm.getActiveNetworkInfo();
		StringBuilder result = new StringBuilder();
		//网络可用
		if (ninfo.isAvailable()) {
			result.append("network type : ").append(ninfo.getTypeName()) //type: mobile / wifi
					.append("\n");
			
			result.append(getContent("http://wap.baidu.com"));
			result_tv.setText(result.toString());
			result = null;
		}
	}

	//获取网络内容
	private String getContent(String uri) {
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(uri);
		HttpResponse resp;
		StringBuilder content = new StringBuilder();
		try {
			resp = client.execute(get);
			HttpEntity entity = resp.getEntity();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(entity.getContent()));
			String line;
			while((line=reader.readLine()) != null) {
				content.append(line);
			}
			reader.close();
			entity = null;
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		return content.toString();
	}
	
}
